package net.cyl.component;

import lombok.extern.slf4j.Slf4j;
import net.cyl.config.SmsConfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;


//@Component
//@Slf4j
//public class SmsComponent {
//    private static final String SMS_URL = "https://dfsns.market.alicloudapi.com/data/send_sms?content=%s&phone_number=%s&template_id=%s";
//    @Autowired
//    private RestTemplate restTemplate;
//    @Autowired
//    private SmsConfig smsConfig;
//
//    /**
//     * 发送短信验证码
//     * @param to
//     * @param templateId
//     * @param value
//     */
//    public void sendSms(String to, String templateId, String value) {
//        String url = String.format(SMS_URL, value, to, templateId);
//        HttpHeaders headers = new HttpHeaders();
//        headers.add("Authorization", "APPCODE " + smsConfig.getAppCode());
//        HttpEntity<String> entity = new HttpEntity<String>(headers);
//        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
//        log.info("url:{}, 发送短信验证码结果：{}", url, response.getBody());
//        if(response.getStatusCode().is2xxSuccessful()){
//            log.info("短信发送成功");
//        }
//        else{
//            log.error("短信发送失败: {}", response.getBody());
//        }
//
//
//    }
//
//
//}

@Component
@Slf4j
public class SmsComponent {

    private static final String SMS_URL = "https://dfsns.market.alicloudapi.com/data/send_sms";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SmsConfig smsConfig;
    @Async("threadPoolTaskExecutor")
    public void sendSms(String content, String templateId, String phoneNumber) {
        long beginTime = System.currentTimeMillis();
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.add("Authorization", "APPCODE " + smsConfig.getAppCode());

        // 手动构建请求体字符串
        String encodedContent = URLEncoder.encode(content, StandardCharsets.UTF_8);
        String encodedTemplateId = URLEncoder.encode(templateId, StandardCharsets.UTF_8);
        String encodedPhoneNumber = URLEncoder.encode(phoneNumber, StandardCharsets.UTF_8);

        String body = String.format("content=%s&template_id=%s&phone_number=%s",
                encodedContent, encodedTemplateId, encodedPhoneNumber);

        HttpEntity<String> requestEntity = new HttpEntity<>(body, headers);

        // 发送请求
        ResponseEntity<String> responseEntity = restTemplate.exchange(
                SMS_URL,
                HttpMethod.POST,
                requestEntity,
                String.class
        );
        long endTime = System.currentTimeMillis();
        log.info("短信发送请求耗时: {} ms", endTime - beginTime);
        if (responseEntity.getStatusCode().is2xxSuccessful()) {
            log.info("短信发送成功，响应结果: {}", responseEntity.getBody());
        } else {
            log.error("短信发送失败，响应结果: {}", responseEntity.getBody());
        }
    }
}
